package fr.axones.pocketagile.ui.controler.command.project.item
{	
	import fr.axones.pocketagile.services.remote.AuthenticationService;
	import fr.axones.pocketagile.services.remote.ProjectItemService;
	import fr.axones.pocketagile.services.remote.ProjectService;
	import fr.axones.pocketagile.services.remote.ProjectUserService;
	import fr.axones.pocketagile.ui.controler.Controler;
	import fr.axones.pocketagile.ui.model.Model;
	import fr.axones.pocketagile.ui.view.authentication.AuthenticationEvent;
	import fr.axones.pocketagile.ui.view.main.project.ProjectEvent;
	import fr.axones.pocketagile.ui.view.main.project.item.ProjectItemEvent;
	import fr.axones.pocketagile.ui.view.main.project.user.ProjectUserEvent;
	import fr.axones.pocketagile.vo.ProjectItemVO;
	
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	public class ProjectItemUpdateCommand
	{
		[Inject(id='projectItemService')]
		public var projectItemService:ProjectItemService;
		
		[Inject(id='controler')]
		public var controler:Controler;
		
		[Inject(id='model')]
		public var model:Model;
		
		public static const SUCCESS:String = "successUpdateProjectUser";
		
		public static const ERROR_UNKNOW:String = "unknowUpdateProjectUser";
		public static const ERROR_CONNECTION:String = "connectionUpdateProjectUser";
		
		public function ProjectItemUpdateCommand()
		{
		}
		
		[Command(selector="updateProjectItem")]
		public function execute(event:ProjectItemEvent):AsyncToken
		{		
			controler.showWaitingPanel();
			
			return projectItemService.updateProjectItem(event.projectItem);
		}
		
		[CommandResult(selector="updateProjectItem")]
		public function result(result:ResultEvent,event:ProjectItemEvent):void
		{			
			controler.hideWaitingPanel();
			
			if(result.result.status<300 && result.result.status>=200)
			{
				for each(var item:ProjectItemVO in model.project.items)
				{
					if(item.id == event.projectItem.id)
					{
						item.value = event.projectItem.value;
						item.name = event.projectItem.name;
					}
				}
				controler.throwSuccess(SUCCESS,result.result.data,result.result.status);
			}
			else
			{
				controler.throwError(ERROR_UNKNOW,null,1);
			}
		}
		
		[CommandError(selector="updateProjectItem")]
		public function fault(fault:FaultEvent,event:ProjectItemEvent):void
		{
			controler.hideWaitingPanel();
			
			controler.throwError(ERROR_CONNECTION,null,0);
		}
	}
}